<script setup>
import { ref, computed, inject, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  UserOutlined, 
  SettingOutlined, 
  LogoutOutlined, 
  DownOutlined,
  HomeOutlined,
  CarOutlined,
  CreditCardOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from './store/user'
import { message } from 'ant-design-vue'
import { RouterView, RouterLink } from 'vue-router'
import { logout } from './api/index'

// 获取注入的语言配置
const locale = inject('locale');

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 初始化用户信息
userStore.initUserFromStorage()

// 计算当前菜单项
const selectedKeys = ref([route.path])

// 监听路由变化，更新选中的菜单项
watch(() => route.path, (newPath) => {
  selectedKeys.value = [newPath];
})

// 检查是否在登录页面
const isLoginPage = computed(() => {
  return route.path === '/login'
})

// 更新菜单选中项
const updateSelectedKeys = () => {
  const path = route.path;
  if (path === '/') selectedKeys.value = ['home']
  else if (path === '/about') selectedKeys.value = ['about']
  else if (path === '/dashboard') selectedKeys.value = ['dashboard']
  else if (path === '/parking-spaces') selectedKeys.value = ['parking-spaces']
  else selectedKeys.value = []
}

// 前往登录页
const goToLogin = () => {
  router.push('/login')
}

// 处理退出登录
const handleLogout = async () => {
  try {
    // 调用登出 API
    const response = await logout();
    
    // 如果调用成功，清除用户状态并跳转
    if (response && response.code === 200) {
      userStore.logout();
      message.success('已成功退出登录');
      router.push('/login');
    } else {
      // 如果API调用失败但需要清除本地状态
      userStore.logout();
      message.warning('登出处理中，请稍等...');
      router.push('/login');
    }
  } catch (error) {
    // 发生错误时，仍然清除本地状态
    console.error('登出错误:', error);
    userStore.logout();
    message.error('退出时发生错误，但已清除本地登录状态');
    router.push('/login');
  }
}

// 定义菜单项
const menuItems = ref([
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '首页',
    path: '/'
  },
  {
    key: '/user',
    icon: () => h(UserOutlined),
    label: '用户管理',
    path: '/user'
  },
  {
    key: '/parking-spaces',
    icon: () => h(CarOutlined),
    label: '车位管理',
    path: '/parking-spaces'
  },
  {
    key: '/quota',
    icon: () => h(CreditCardOutlined),
    label: '额度消耗维护',
    path: '/quota'
  },
  {
    key: '/settings',
    icon: () => h(SettingOutlined),
    label: '系统设置',
    path: '/settings'
  }
]);
</script>

<template>
  <a-config-provider :locale="locale">
    <div class="app">
      <a-layout v-if="!isLoginPage" class="layout">
        <a-layout-header class="header">
          <div class="logo">
            <img src="./assets/Logo.png" alt="辉瑞停车管理系统" />
            <h1>停车管理系统</h1>
          </div>
          <div class="header-content">
            <a-menu
              v-model:selectedKeys="selectedKeys"
              mode="horizontal"
              class="main-menu"
            >
              <a-menu-item key="/">
                <router-link to="/">员工管理</router-link>
              </a-menu-item>
              <!-- <a-menu-item key="/user">
                <router-link to="/user">员工管理</router-link>
              </a-menu-item> -->
              <a-menu-item key="/parking-spaces">
                <router-link to="/parking-spaces">车位管理</router-link>
              </a-menu-item>
              <a-menu-item key="/quota">
                <router-link to="/quota">额度消耗维护</router-link>
              </a-menu-item>
              <a-menu-item key="/settings">
                <router-link to="/settings">系统设置</router-link>
              </a-menu-item>
            </a-menu>
            
            <div class="user-menu">
              <a-dropdown v-if="userStore.isLoggedIn">
                <a class="ant-dropdown-link" @click.prevent>
                  <a-avatar size="small"><template #icon><UserOutlined /></template></a-avatar>
                  <span class="username">{{ userStore.user?.name || userStore.user?.username }}</span>
                  <DownOutlined />
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleLogout">
                      <LogoutOutlined />
                      退出登录
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button v-else type="primary" @click="goToLogin">登录</a-button>
            </div>
          </div>
        </a-layout-header>
        <a-layout-content class="content">
          <div class="content-container">
            <router-view />
          </div>
        </a-layout-content>
        <a-layout-footer style="text-align: center">
          停车位预约系统 ©2023 Created by Pfizer
        </a-layout-footer>
      </a-layout>
      
      <!-- 登录页没有顶部导航和底部 -->
      <router-view v-if="isLoginPage" />
    </div>
  </a-config-provider>
</template>

<style scoped>
.app {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0 24px;
  display: flex;
  align-items: center;
  height: 64px;
}

.logo {
  display: flex;
  align-items: center;
  height: 64px;
  padding-right: 24px;
}

.logo img {
  height: 40px;
  margin-right: 12px;
}

.logo h1 {
  margin: 0;
  font-size: 18px;
  color: #1890ff;
  white-space: nowrap;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}

.main-menu {
  border-bottom: none;
  background: transparent;
}

:deep(.ant-menu-horizontal) {
  border-bottom: none;
  line-height: 64px;
}

:deep(.ant-menu-item) {
  border-bottom: 2px solid transparent;
}

:deep(.ant-menu-item-selected),
:deep(.ant-menu-item:hover) {
  border-bottom: 2px solid #1890ff;
  color: #1890ff;
}

.user-menu {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.ant-dropdown-link {
  display: flex;
  align-items: center;
  color: rgba(0, 0, 0, 0.85);
  cursor: pointer;
}

.username {
  margin: 0 8px;
}

.content {
  padding: 0 50px;
  flex: 1;
}

.content-container {
  background: #fff;
  padding: 24px;
  min-height: 280px;
  margin-top: 24px;
  margin-bottom: 24px;
}
</style>
